import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../util/Toast.dart';
import 'package:flutter_aygsh/entity/address_entity.dart';
import 'package:flutter_aygsh/http/Api.dart';
import 'package:flutter_aygsh/http/HttpUtil.dart';
import 'package:flutter_aygsh/util/AppSaveInfoUtil.dart';
import '../../base/Constant.dart';
import 'addAddress.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../../util/SignUtil.dart';
import '../../event/AddrEvent.dart';
import '../../base/application.dart';

class MyAddressPage extends StatefulWidget {
  int type = 0;
  MyAddressPage({Key key, this.type}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyAddressView();
  }
}

class MyAddressView extends State<MyAddressPage> {
  List<AddressListDataData> dataList = new List();
  int page = 1;
  String token = "";
  EasyRefreshController _controller = EasyRefreshController();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      appBar: new AppBar(
        title: Text(widget.type == 0 ? '我的地址' : '选择地址',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.2,
        actions: <Widget>[
          GestureDetector(
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.fromLTRB(0, 0, 13, 0),
              child: Text(
                '添加地址',
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                    color: Colors.black),
              ),
            ),
            onTap: () {
              Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                return new AddAddressPage();
              }));
            },
          )
        ],
      ),
      body: new Container(
        color: divideColor,
        child: new EasyRefresh(
          header: MaterialHeader(),
          footer: MaterialFooter(),
          enableControlFinishRefresh: true,
          enableControlFinishLoad: true,
          controller: _controller,
          child: ListView.separated(
              itemBuilder: _renderRow,
              separatorBuilder: (BuildContext context, int index) {
                return Container(
                  color: divideColor,
                  height: 1,
                );
              },
              itemCount: dataList == null ? 0 : dataList.length),
          onRefresh: () async {
            page = 1;
            loadList();
          },
          onLoad: () async {
            page++;
            loadList();
          },
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      child: new Container(
        color: Colors.white,
        padding: EdgeInsets.all(15.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            new Row(
              children: <Widget>[
                Text(
                  dataList[index].consignee == null
                      ? ""
                      : dataList[index].consignee,
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                      color: Colors.black),
                ),
                Container(
                  width: DP_10,
                ),
                Expanded(
                  flex: 3,
                  child: Text(
                    dataList[index].contact_number,
                    style: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                        color: Colors.black87),
                  ),
                )
              ],
            ),
            Container(
              padding: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(DP_10), 0, 0),
              child: Text(
                dataList[index].province +
                    dataList[index].city +
                    dataList[index].county +
                    dataList[index].detail_address,
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                    color: Colors.black87),
              ),
            ),
            new Container(
              child: new Row(
                children: <Widget>[
                  Checkbox(
                      value: dataList[index].is_default == 'Y',
                      activeColor: mainColor,
                      checkColor: white,
                      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      onChanged: (bool x) {
                        dataList[index].is_default =
                            (dataList[index].is_default == 'Y' ? 'N' : 'Y');
                        change(index);

                        setState(() {});
                      }),
                  Text('默认地址',
                      style: TextStyle(
                          color: Colors.black54,
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),
                  Expanded(
                    child: Text(''),
                  ),
                  new GestureDetector(
                    onTap: () {
                      deleteAddress(context, index);
                    },
                    child: new Container(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20),
                          2,
                          ScreenUtil.getInstance().setHeight(DP_20),
                          2),
                      decoration: new BoxDecoration(
                          borderRadius: BorderRadius.circular(5.0),
                          border:
                              Border.all(color: Colors.black54, width: 1.0)),
                      child: Text(
                        '删除',
                        style: TextStyle(
                            fontSize:
                                ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                            color: Colors.black54),
                      ),
                    ),
                  ),
                  new GestureDetector(
                    onTap: () {
                      Navigator.of(context)
                          .push<String>(MaterialPageRoute(builder: (context) {
                        return new AddAddressPage(item: dataList[index]);
                      })).then((value) {
                        if (value != null) {
                          page = 1;
                          loadList();
                        }
                      });
                    },
                    child: new Container(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20),
                          2,
                          ScreenUtil.getInstance().setHeight(DP_20),
                          2),
                      margin: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20), 0, 0, 0),
                      decoration: new BoxDecoration(
                          borderRadius: BorderRadius.circular(5.0),
                          border: Border.all(color: mainColor, width: 1.0)),
                      child: Text(
                        '编辑',
                        style: TextStyle(
                            fontSize:
                                ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                            color: mainColor),
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
      onTap: () {
        if (widget.type == 1) {
          Navigator.of(context).pop(dataList[index]);
        }
      },
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      loadList();
    });

    APPLIC.eventBus.on<AddrEvent>().listen((event) {
      getString(TOKEN).then((value) {
        token = value;
        page = 1;
        loadList();
      });
    });
  }

  loadList() async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_ADDRESS_LIST),
      "token": token,
      "p": page.toString(),
      "per": "10"
    });
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_ADDRESS_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (mounted) if (page == 1) {
      _controller.finishRefresh();
    } else {
      _controller.finishLoad();
    }
    if (userMap['code'] != 1) {
      // Fluttertoast.showToast(msg: userMap['msg']);
      Toast.toast(context, msg: userMap['msg']);
      return;
    }
    AddressListEntity homeListEntity = new AddressListEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          dataList.addAll(homeListEntity.data.datas);
        } else {
          dataList.addAll(homeListEntity.data.datas);
        }
      });
  }

  deleteAddress(BuildContext context, int index) {
    showDialog(
      context: context,
      builder: (context) => new AlertDialog(
        title: new Text('提示'),
        content: new Text('确定删除该收货地址吗，删除后不可撤回'),
        actions: <Widget>[
          new FlatButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: new Text(
              '取消',
              style: TextStyle(color: Colors.grey),
            ),
          ),
          new FlatButton(
            onPressed: () {
              del(index);
              Navigator.of(context).pop(false);
            },
            child: new Text('确定删除', style: TextStyle(color: mainColor)),
          ),
        ],
      ),
    );
  }

  del(int index) async {
    Map map = new Map();
    map['token'] = token;
    map['id'] = dataList[index].id;
    map['sign_type'] = createSignType(Api.URL_ADDRESS_DEL);
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_ADDRESS_DEL, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    // Fluttertoast.showToast(msg: msg);
    Toast.toast(context, msg: userMap['msg']);
    // print(userMap['data'].toString());
    if (code == 1 && mounted) {
      dataList.removeAt(index);
      setState(() {});
    }
  }

  change(int index) async {
    Map map = new Map();
    map['token'] = token;
    map['id'] = dataList[index].id;
    map['address_id'] = dataList[index].id;
    map['province'] = dataList[index].province;
    map['city'] = dataList[index].city;
    map['county'] = dataList[index].county;
    map['detail_address'] = dataList[index].detail_address;
    map['consignee'] = dataList[index].consignee;
    map['contact_number'] = dataList[index].contact_number;
    map['is_default'] = dataList[index].is_default == 'N' ? "N" : "Y";
    map['sign_type'] = createSignType(Api.URL_ADDRESS_EDIT);
    Response<String> response =
        await HttpUtil().post(Api.URL_ADDRESS_EDIT, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    // Navigator.of(context).pop(1);
    // print(userMap['data'].toString());
    if (code == 1 && mounted) {
      page = 1;
      loadList();
    } else {
      // Fluttertoast.showToast(msg: msg);
      Toast.toast(context, msg: userMap['msg']);
    }
  }
}
